import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { MaterialDonateRecord } from '../../entities/MaterialDonateRecord.entity'
import { MaterialDonateWithMaterial } from '../../types/admin'

@Provide()
export class MaterialDonateRecordService {
  @InjectEntityModel(MaterialDonateRecord)
  repo!: Repository<MaterialDonateRecord>

  async list(queryInfo: any) {
    const { page = 1, pageSize = 10 } = queryInfo
    // 创建查询构建器，连表查询捐赠人姓名，物资名称，物资数量，捐赠时间
    const queryBuilder = this.repo.createQueryBuilder('mdr')
      .leftJoin('mdr.materialDonate', 'm') // 连接物资捐赠需求表
      .leftJoin('m.material', 'mm')   // 连接物资表
      .leftJoin('mdr.user', 'u')     // 连接用户表
      // 选择需要的字段
      .select([
        'mdr.id AS id',
        'u.nickname AS donorName',   // 捐赠人姓名
        'mm.name AS materialName',    // 物资名称
        'mdr.count AS count',        // 物资数量
        'mdr.createTime AS donateTime' // 捐赠时间
      ])
      .orderBy('mdr.id', 'DESC');
    // 获取总数
    const total = await queryBuilder.getCount();
    
    // 获取分页数据
    const items = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getRawMany();

    return {
      total,
      items: items as MaterialDonateWithMaterial[],
    }
  }
}
